package com.itheima.pay.ali;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("easyalipay")
public class EasyAliPayController {


    @GetMapping("precreate/{out_trade_no}")
    public AlipayTradePrecreateResponse precreate(@PathVariable("out_trade_no") String out_trade_no) {

        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());

        try {
            // 2. 发起API调用（以创建当面付收款二维码为例）
            AlipayTradePrecreateResponse response =
                    Factory
                    .Payment
                    .FaceToFace()
                    .preCreate("Apple iPhone11 128G", out_trade_no, "0.1");

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
            } else {
                System.err.println("调用失败，原因：" + response.msg + "，" + response.subMsg);
            }

            return response;
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    @Autowired
    AliPayProperties aliPayProperties;



    @GetMapping("query/{out_trade_no}")
    public AlipayTradeQueryResponse query(@PathVariable("out_trade_no") String out_trade_no) {

        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());

        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(out_trade_no);

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
            } else {
                System.err.println("调用失败，原因：" + response.msg + "，" + response.subMsg);
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }



    @GetMapping("refund/{out_trade_no}")
    public AlipayTradeRefundResponse refund(@PathVariable("out_trade_no") String out_trade_no) {

        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());

        try {
            AlipayTradeRefundResponse response =
                    Factory.Payment.Common().refund(out_trade_no, "0.1");

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
            } else {
                System.err.println("调用失败，原因：" + response.msg + "，" + response.subMsg);
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    @GetMapping("refundquery/{out_trade_no}/{out_request_no}")
    public AlipayTradeFastpayRefundQueryResponse refundQuery(@PathVariable("out_trade_no") String out_trade_no,
                                                 @PathVariable("out_request_no") String out_request_no) {
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());

        try {
            AlipayTradeFastpayRefundQueryResponse response = Factory.Payment.Common()
                    .queryRefund(out_trade_no, out_request_no);

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
            } else {
                System.err.println("调用失败，原因：" + response.msg + "，" + response.subMsg);
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    private Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipay.com";
        config.signType = "RSA2";
        config.appId = aliPayProperties.getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = aliPayProperties.getMerchantPrivateKey();
        config.alipayPublicKey =aliPayProperties.getAlipayPublicKey();


        //注：证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径，优先从文件系统中加载，加载失败后会继续尝试从CLASS_PATH中加载
        //config.merchantCertPath = "<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->";
        //config.alipayCertPath = "<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->";
        //config.alipayRootCertPath = "<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->";
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可

        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = "";
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        config.encryptKey = aliPayProperties.getEncryptKey();
        return config;
    }

}
